from cwrap.config import Config, File
import textwrap
import shutil,os

pyx_header = textwrap.dedent(
"""
cimport _TwoPhaseHTDP
"""
)

def generate_pxd(fName):
    config = Config('gccxml', files=[File(fName)])
    config.generate()
    
def strip_args(args):
    out_args = []
    strip_args = args.split(',')
    for arg in strip_args:
        arg = arg.strip()
        is_pointer = arg.find('*')
        
        if is_pointer:
            arg = arg.replace('*','')
        #Try to split at the space
        var_type,arg = arg.split(' ')
        out_args.append(arg)
    return out_args
        
def parse_pxd(fName):
    lines = open(fName,'r').readlines()
    with open(fName.split('.')[0].lstrip('_')+'.pyx','w') as f:
        f.write('cimport '+fName.split('.')[0]+'\n\n')
        for line in lines:
            line = line.strip()
            if line.startswith('double'):
                func,args = line.split('(')
                # Remove the output parameter
                returns,func = func.split(' ')
                # Get the input arguments
                args = args.split(')')[0]
                # Get the args without the variable types
                
                
                signature = 'cpdef {returns:s} {func:s}({args:s}):'.format(returns = returns,
                                                                          func = func,
                                                                          args = args)
                the_call = '    return {header:s}.{func:s}({args:s})'.format(args = ', '.join(strip_args(args)),
                                                                             header = fName.split('.')[0],
                                                                             func = func)
                
                f.write(signature+'\n')
                f.write(the_call+'\n')
                f.write(''+'\n')
    
if __name__ == '__main__':
    generate_pxd('../../src/TwoPhaseHTDP.h')
    parse_pxd('_TwoPhaseHTDP.pxd')
    shutil.move('_TwoPhaseHTDP.pxd',os.path.join('ThermalCorr','_TwoPhaseHTDP.pxd'))
    shutil.move('TwoPhaseHTDP.pyx',os.path.join('ThermalCorr','TwoPhaseHTDP.pyx'))